// function qs(ele) {
//     return document.querySelector(ele)
// }

// 接口地址：https://www.apifox.cn/apidoc/shared-36f0cbc0-9064-44bc-850a-805e263bf494/api-25827426
// 简化箭头函数
const qs = element => document.querySelector(element)

axios.defaults.baseURL = 'http://124.223.14.236:3001/api'

async function init() {
    const { data: res } = await axios.get('/city/province')
    console.log(res.data);  //省份数组

    //map join 渲染
    const provinceStr = res.data.map(
        (item) => `<option value="${item.province}">${item.name}</option>`
    ).join('')
    // console.log(provinceStr)
    qs('#province').innerHTML = '<option value="">请选择省份</option>' + provinceStr
    //34是安徽的编码，设置默认展示安徽
    qs('#province').value = 34

    //获得安徽的市--------------------------------------------
    const {
        data: { data: cityData }, } = await axios.get('/city/city', {
            params: {
                provinceCode: '34',
            }
        })
    // console.log(cityData);

    const cityStr = cityData.map(item => `<option value="${item.city}">${item.name}</option>`).join('')

    qs('#city').innerHTML = `<option value="">请选择城市</option>` + cityStr

    qs('#city').value = '01'

    // 获得合肥的区--------------------------------------------
    const {
        data: { data: townData }, } = await axios.get('/city/area', {
            params: {
                provinceCode: '34',
                cityCode: '01'
            }
        })
    // console.log(townData);

    const townStr = townData.map(item => `<option value="${item.area}">${item.name}</option>`).join('')

    qs('#county').innerHTML = `<option value="">请选择区</option>` + townStr

    qs('#county').value = '02'
}
init()

//省份改变，获得市-------------------------------------------------
qs('#province').addEventListener('change', async function () {
    // console.log(this.value);
    const {
        data: { data: cityData }, } = await axios.get('/city/city', {
            params: {
                provinceCode: this.value,
            }
        })
    // console.log(cityData);

    const cityStr = cityData.map(item => `<option value="${item.city}">${item.name}</option>`).join('')

    qs('#city').innerHTML = `<option value="">请选择城市</option>` + cityStr
    // 省份改变，清空区县
    qs('#county').innerHTML = `<option value="">请选择区</option>`
})

//市改变，获得区-------------------------------------------------
qs('#city').addEventListener('change', async function () {
    // console.log(this.value);
    const {
        data: { data: areaData }, } = await axios.get('/city/area', {
            params: {
                provinceCode: qs('#province').value,
                cityCode: this.value
            }
        })
    // console.log(cityData);

    const areaStr = areaData.map(item => `<option value="${item.area}">${item.name}</option>`).join('')

    qs('#county').innerHTML = `<option value="">请选择区</option>` + areaStr
})

